#include <stdlib.h>
#include <string.h>
#include <config.h>
#include <stm32f0xx.h>
#include <device.h>
#include <printk.h>
#include "stm32_usart.h"
#include <init.h>


#ifdef configUSING_SERIAL

/* USART1 */
#define UART1_GPIO_TX			GPIO_Pin_9
#define UART1_GPIO_TX_SOURCE	GPIO_PinSource9
#define UART1_GPIO_RX			GPIO_Pin_10
#define UART1_GPIO_RX_SOURCE	GPIO_PinSource10
#define UART1_GPIO_AF			GPIO_AF_1
#define UART1_GPIO				GPIOA

/* USART2 */
#define UART2_GPIO_TX			GPIO_Pin_2
#define UART2_GPIO_TX_SOURCE	GPIO_PinSource2
#define UART2_GPIO_RX			GPIO_Pin_3
#define UART2_GPIO_RX_SOURCE	GPIO_PinSource3
#define UART2_GPIO_AF			GPIO_AF_1
#define UART2_GPIO				GPIOA

/* STM32 uart driver */
struct stm32_uart
{
    USART_TypeDef* uart_device;
    IRQn_Type irq;
};

static void uart_interrupt_handler(struct serial_device *serial);

#if defined(configUSING_UART1)
struct stm32_uart uart1 =
{
    USART1,
    USART1_IRQn,
};
static struct serial_device serial1;

void USART1_IRQHandler(void)
{
    uart_interrupt_handler(&serial1);
}
#endif

#if defined(configUSING_UART2)
struct stm32_uart uart2 =
{
    USART2,
    USART2_IRQn,
};
static struct serial_device serial2;

void USART2_IRQHandler(void)
{
    uart_interrupt_handler(&serial2);
}
#endif

static void RCC_Configuration(void)
{
#ifdef configUSING_UART1
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
#endif

#ifdef configUSING_UART2
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
#endif
}
static void GPIO_Configuration(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

#ifdef configUSING_UART1
	GPIO_PinAFConfig(UART1_GPIO, UART1_GPIO_TX_SOURCE, UART1_GPIO_AF);
	GPIO_PinAFConfig(UART1_GPIO, UART1_GPIO_RX_SOURCE, UART1_GPIO_AF);

	GPIO_InitStructure.GPIO_Pin = UART1_GPIO_TX ;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(UART1_GPIO, &GPIO_InitStructure);
    
    GPIO_InitStructure.GPIO_Pin =  UART1_GPIO_RX;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
	GPIO_Init(UART1_GPIO, &GPIO_InitStructure);
#endif

#ifdef configUSING_UART2
	GPIO_PinAFConfig(UART2_GPIO, UART2_GPIO_TX_SOURCE, UART2_GPIO_AF);
	GPIO_PinAFConfig(UART2_GPIO, UART2_GPIO_RX_SOURCE, UART2_GPIO_AF);

	GPIO_InitStructure.GPIO_Pin = UART2_GPIO_TX | UART2_GPIO_RX;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(UART2_GPIO, &GPIO_InitStructure);
#endif
}
static void NVIC_Configuration(struct stm32_uart* uart, uint8_t priority)
{
    NVIC_InitTypeDef NVIC_InitStructure;

    /* Enable the USART Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = uart->irq;
    NVIC_InitStructure.NVIC_IRQChannelPriority = priority;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}
static err_t stm32_configure(struct serial_device *serial, struct serial_configure *cfg)
{
    USART_InitTypeDef USART_InitStructure;
    struct stm32_uart* uart = (struct stm32_uart *)serial->parent.user_data;

    USART_InitStructure.USART_BaudRate = cfg->baud_rate;

    if (cfg->data_bits == DATA_BITS_8)
        USART_InitStructure.USART_WordLength = USART_WordLength_8b;

    if (cfg->stop_bits == STOP_BITS_1)
        USART_InitStructure.USART_StopBits = USART_StopBits_1;
    else if (cfg->stop_bits == STOP_BITS_2)
        USART_InitStructure.USART_StopBits = USART_StopBits_2;
    
    if (cfg->parity == PARITY_NONE)
        USART_InitStructure.USART_Parity = USART_Parity_No;
    else if (cfg->parity == PARITY_EVEN)
    {
        USART_InitStructure.USART_Parity = USART_Parity_Even;
        USART_InitStructure.USART_WordLength = USART_WordLength_9b;
    }
    else if (cfg->parity == PARITY_ODD)
    {
        USART_InitStructure.USART_Parity = USART_Parity_Odd;
        USART_InitStructure.USART_WordLength = USART_WordLength_9b;
    }
    
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(uart->uart_device, &USART_InitStructure);

    /* Enable USART */
    USART_Cmd(uart->uart_device, ENABLE);
    /* enable interrupt */

    USART_SetReceiverTimeOut(uart->uart_device, 20);
    USART_ReceiverTimeOutCmd(uart->uart_device, ENABLE);

    USART_ITConfig(uart->uart_device, USART_IT_RTO, ENABLE);
    return 0;
}

static err_t stm32_control(struct serial_device *serial, int cmd, void *arg)
{
    struct stm32_uart* uart = (struct stm32_uart *)serial->parent.user_data;

    switch (cmd)
    {
    case DEVICE_CTRL_CLR_INT:
        USART_ITConfig(uart->uart_device, USART_IT_RXNE, DISABLE);
        break;
    case DEVICE_CTRL_SET_INT:
        USART_ITConfig(uart->uart_device, USART_IT_RXNE, ENABLE);
        break;
    case DEVICE_CTRL_CLR_TX_INT:
        USART_ITConfig(uart->uart_device, USART_IT_TXE, DISABLE);
        break;
    case DEVICE_CTRL_SET_TX_INT:
        USART_ITConfig(uart->uart_device, USART_IT_TXE, ENABLE);
        break;
    }

    return 0;
}

static int stm32_putc(struct serial_device *serial, char c)
{
    struct stm32_uart* uart = (struct stm32_uart *)serial->parent.user_data;

    while (!(uart->uart_device->ISR & USART_FLAG_TXE));
    uart->uart_device->TDR = c;
    //USART_SendData((uart->uart_device),c);
    return 1;
}

static int stm32_getc(struct serial_device *serial)
{
    int ch = -1;
    struct stm32_uart* uart = (struct stm32_uart *)serial->parent.user_data;

    if (uart->uart_device->ISR & USART_FLAG_RXNE)
    {
        ch = uart->uart_device->RDR & 0xff;
    }

    return ch;
}
static const struct uart_ops stm32_uart_ops =
{
    stm32_configure,
    stm32_control,
    stm32_putc,
    stm32_getc,
};

static void uart_interrupt_handler(struct serial_device *serial)
{
    USART_TypeDef *uart_dev = ((struct stm32_uart *)serial->parent.user_data)->uart_device;

    if (USART_GetFlagStatus(uart_dev, USART_FLAG_ORE))
    {
        USART_ClearFlag(uart_dev,USART_FLAG_ORE); //read SR
        USART_ReceiveData(uart_dev); //read DR
        USART_ClearITPendingBit(uart_dev, USART_IT_ORE);
    }

    if (USART_GetITStatus(uart_dev, USART_IT_TXE))
    {
        serial_device_isr(serial, SERIAL_EVENT_TX_RDY);
    }

    if (USART_GetITStatus(uart_dev, USART_IT_RXNE))
    {
        serial_device_isr(serial, SERIAL_EVENT_RX_IND);
    }

    if (USART_GetITStatus(uart_dev, USART_IT_RTO))
    {
        USART_ClearITPendingBit(uart_dev, USART_IT_RTO);
        serial_device_isr(serial, SERIAL_EVENT_RX_TIMEOUT);
    }
}

int board_usart_init(void)
{
    struct stm32_uart* uart;
    struct serial_configure config = SERIAL_CONFIG_DEFAULT;

    RCC_Configuration();
    GPIO_Configuration();

#ifdef configUSING_UART1
    uart = &uart1;
    config.bufsz   = 0x100;
    serial1.ops    = &stm32_uart_ops;
    serial1.config = config;

    NVIC_Configuration(&uart1, 0);

    serial_device_register(&serial1, "mbus", DEVICE_FLAG_INT_RX | DEVICE_FLAG_INT_TX,
                          uart);
#endif

#ifdef configUSING_UART2
    uart = &uart2;

    config.bufsz   = 0x100;
    serial2.ops    = &stm32_uart_ops;
    serial2.config = config;

    NVIC_Configuration(&uart2, 1);

    /* register UART1 device */
    serial_device_register(&serial2, "uart2", DEVICE_FLAG_INT_RX | DEVICE_FLAG_INT_TX,
                          uart);
#endif /* RT_USING_UART2 */
	return 0;
}

device_initcall(board_usart_init);

#endif

